/**
  Basic sample TCP/IP Client programme in C
  Socket family -> AF_INET
  socket_type   -> SOCK_STREAM
  
  This program connects to a server, and prints whatever it returns.
  Change the _PORT and _ADDR values to point to your server.
  
  Skelten of a client program
  socket()
  connect()
  write()
  read()
  close()
**/

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define _PORT 12345
#define _ADDRESS "127.0.0.1"

int main()
{
  struct sockaddr_in addr;
  int sock;
  int n=0;
  char buffer[128];
  char *msg="Hello I am client";
  
  /* Get socket descriptor */
  sock=socket(AF_INET,SOCK_STREAM,0);
  if( sock == -1 )
  {
    perror("Error in creating socket");
    return 1;
  }
  
  memset(&addr,0,sizeof(struct sockaddr_in));
  addr.sin_family=AF_INET;
  addr.sin_port=htons(_PORT);
  
  /* Get address converted into network byte order */
  if(inet_pton(AF_INET,_ADDRESS,&addr.sin_addr)<0)
  {
    perror("inetpton failed");
    return 0;
  }
  
  /* Connect to the specified address and port */
  if(connect(sock,(struct sockaddr*)&addr,sizeof(addr)) < 0)
  {
    perror("Connection failed");
    return 1;
  }
  
  printf("Connected\n");


  n=write(sock,msg,strlen(msg));
  if( n>0 ){
    buffer[n]='\0';
    printf("Number of bytes written = '%d' \n",n);
  }
  
  memset(buffer,0,sizeof(buffer));
  n=read(sock,buffer,sizeof(buffer)-1);
  if( n>0 ){
    buffer[n]='\0';
    printf("Number of bytes read = '%d' \n",n);
    printf("msg received = '%s'",buffer);
  }
  
  /* Close socket */
  close(sock);
  
}
